using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;

namespace JGSY.CMS.LowCode.Platform.Application.Services
{
    /// <summary>
    /// 用户角色应用服务
    /// 提供用户与角色的分配、查询等用户角色关系管理相关业务功能
    /// </summary>
    [JGSY.CMS.LowCode.Platform.Infrastructure.Services.LogOperation]
    public class UserRoleAppService : IUserRoleAppService
    {
        /// <summary>
        /// 用户角色仓储接口
        /// </summary>
        private readonly Domain.Interfaces.IUserRoleRepository _userRoleRepository;
        
        /// <summary>
        /// 构造函数，注入用户角色仓储
        /// </summary>
        /// <param name="userRoleRepository">用户角色仓储接口</param>
        public UserRoleAppService(Domain.Interfaces.IUserRoleRepository userRoleRepository)
        {
            _userRoleRepository = userRoleRepository;
        }
        
        /// <summary>
        /// 获取所有用户角色关系
        /// </summary>
        /// <returns>用户角色关系列表</returns>
        public async Task<IEnumerable<UserRoleDto>> GetAllAsync()
        {
            var userRoles = await _userRoleRepository.GetAllAsync();
            return userRoles.Select(ur => new UserRoleDto { UserId = ur.UserId, RoleId = ur.RoleId });
        }

        /// <summary>
        /// 添加用户角色关系
        /// 为指定用户分配角色
        /// </summary>
        /// <param name="dto">用户角色关系数据传输对象</param>
        /// <returns>添加任务</returns>
        public async Task AddAsync(UserRoleDto dto)
        {
            var entity = new Domain.Entities.UserRole { UserId = dto.UserId, RoleId = dto.RoleId };
            await _userRoleRepository.AddAsync(entity);
        }

        /// <summary>
        /// 移除用户角色关系
        /// 取消用户的指定角色分配
        /// </summary>
        /// <param name="userId">用户标识符</param>
        /// <param name="roleId">角色标识符</param>
        /// <returns>移除任务</returns>
        public async Task RemoveAsync(long userId, long roleId)
        { 
            await _userRoleRepository.RemoveAsync(userId, roleId);
        }

        /// <summary>
        /// 获取指定用户的所有角色
        /// </summary>
        /// <param name="userId">用户标识符</param>
        /// <returns>角色列表</returns>
        public async Task<IEnumerable<RoleDto>> GetRolesByUserAsync(long userId)
        {
           
            var roles = await _userRoleRepository.GetRolesByUserAsync(userId);
            return roles.Select(r => new RoleDto { Id = r.Id, Name = r.Name });
        }
    }
}
